package com.changgou.goods.service.impl;

import com.changgou.goods.dao.AlbumDao;
import com.changgou.goods.service.AlbumService;
import com.changgou.pojo.Album;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * @author ：Raoness
 * @date ：Created in 2019/7/23 18:13
 * @description ：
 * @version: 1.0
 */
@Service
public class AlbumServiceImpl implements AlbumService {

    @Autowired
    private AlbumDao albumDao;

    @Override
    public List<Album> findAll() {
        return albumDao.selectAll();
    }

    @Override
    public Album findById(Integer id) {
        return albumDao.selectByPrimaryKey(id);
    }

    @Override
    public void add(Album album) {
        albumDao.insertSelective(album);
    }

    @Override
    public void update(Album album) {
        albumDao.updateByPrimaryKeySelective(album);
    }

    @Override
    public void delete(Integer id) {
        albumDao.deleteByPrimaryKey(id);
    }

    @Override
    public List<Album> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return albumDao.selectByExample(example);
    }

    @Override
    public Page<Album> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Album> albumList = (Page<Album>) albumDao.selectAll();
        return albumList;
    }

    @Override
    public Page<Album> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Album> albumList = (Page<Album>) albumDao.selectByExample(example);
        return albumList;
    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Album.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            if (searchMap.get("title") != null && !"".equals(searchMap.get("title"))) {
                criteria.andLike("title", "%" + searchMap.get("title") + "%");
            }
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andEqualTo("image", searchMap.get("image"));
            }
        }
        return example;
    }
}
